<template>
  <div class="container">
    <a-card class="general-card" title="充电桩列表">
      <!-- 搜索表单 -->
      <div class="filter-container">
        <a-form :model="searchForm" class="filter-form">
          <div class="filter-row">
            <div class="filter-item">
              <span class="filter-label">设备编号：</span>
              <a-input v-model="searchForm.code" placeholder="请输入设备编号" allow-clear class="filter-input" />
            </div>
            <div class="filter-item">
              <span class="filter-label">充电桩名称：</span>
              <a-input v-model="searchForm.name" placeholder="请输入充电桩名称" allow-clear class="filter-input" />
            </div>
            <div class="filter-item">
              <span class="filter-label">所属站点：</span>
              <a-select v-model="searchForm.chargingGroupId" placeholder="请选择站点" allow-clear allow-search
                class="filter-select">
                <a-option v-for="station in stationList" :key="station.id" :value="station.id">
                  {{ station.name }}
                </a-option>
              </a-select>
            </div>
            <div class="filter-item">
              <span class="filter-label">设备状态：</span>
              <a-select v-model="searchForm.status" placeholder="请选择状态" allow-clear class="filter-select">
                <a-option :value="1">
                  <a-tag color="green" size="small">在线</a-tag>
                </a-option>
                <a-option :value="0">
                  <a-tag color="red" size="small">离线</a-tag>
                </a-option>
              </a-select>
            </div>
            <div class="filter-item filter-actions">
              <a-button type="primary" @click="search">
                <template #icon>
                  <icon-search />
                </template>
                搜索
              </a-button>
              <a-button @click="reset" class="reset-btn">
                <template #icon>
                  <icon-refresh />
                </template>
                重置
              </a-button>
              <a-button type="primary" @click="openAddDialog" class="add-btn">
                <template #icon>
                  <icon-plus />
                </template>
                新增
              </a-button>
              <a-button type="primary" status="success" @click="openImportDialog" class="import-btn">
                <template #icon>
                  <icon-upload />
                </template>
                批量导入
              </a-button>
              <a-button type="primary" status="warning" :disabled="!hasSelected" @click="handleExportQrCodes"
                class="export-btn">
                <template #icon>
                  <icon-download />
                </template>
                导出二维码
              </a-button>
            </div>
          </div>
        </a-form>
      </div>

      <!-- 表格 -->
      <a-table :loading="loading" :data="tableData" :pagination="pagination" @page-change="onPageChange"
        @page-size-change="onPageSizeChange" :row-selection="{
          type: 'checkbox',
          showCheckedAll: true,
          onlyCurrent: false
        }" v-model:selected-keys="selectedKeys" row-key="id" stripe>
        <template #columns>
          <a-table-column title="序号" :width="80" align="center">
            <template #cell="{ rowIndex }">
              {{ (pagination.current - 1) * pagination.pageSize + rowIndex + 1 }}
            </template>
          </a-table-column>
          <a-table-column title="设备编号" data-index="code" :width="150" />
          <a-table-column title="充电桩名称" data-index="name" :width="150" />
          <a-table-column title="设备状态" :width="120">
            <template #cell="{ record }">
              <a-tag :color="record.status === 1 ? 'green' : 'red'">
                {{ record.status === 1 ? '在线' : '离线' }}
              </a-tag>
            </template>
          </a-table-column>
          <a-table-column title="枪数量" data-index="socketCount" :width="120" />
          <a-table-column title="所属站点" data-index="chargingGroupName" :width="150" />
          <a-table-column title="操作" :width="200" fixed="right" align="center">
            <template #cell="{ record }">
              <a-space>
                <a-button type="text" size="small" @click="openEditDialog(record)">
                  <template #icon><icon-edit /></template>
                  编辑
                </a-button>
                <a-button type="text" status="danger" size="small" @click="handleDelete(record)">
                  <template #icon><icon-delete /></template>
                  删除
                </a-button>
              </a-space>
            </template>
          </a-table-column>
        </template>
      </a-table>

      <!-- 新增/编辑对话框 -->
      <a-modal v-model:visible="dialogVisible" :title="isEdit ? '编辑充电桩' : '新增充电桩'" @cancel="closeDialog"
        @before-ok="handleSubmit">
        <charging-form ref="chargingFormRef" :charging-group-id="form.chargingGroupId" :is-edit="isEdit"
          :edit-data="editData" />
      </a-modal>

      <!-- 导入对话框 -->
      <import-dialog v-model:visible="importVisible" :charging-group-id="form.chargingGroupId"
        @success="handleImportSuccess" />
    </a-card>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted, nextTick, computed } from 'vue';
import { Message, Modal } from '@arco-design/web-vue';
import type { FormInstance } from '@arco-design/web-vue';
import {
  getChargingList,
  addCharging,
  updateCharging,
  deleteCharging,
  getChargingQrCodes,
  type ChargingData,
  type ChargingListParams,
  type ChargingWithQrCodesVo
} from '@/api/charging/index';
import { getAllCarChargingGroups } from '@/api/car-charging-group';
import ImportDialog from './components/import-dialog.vue';
import ChargingForm from './components/charging-form.vue';
import {
  IconSearch,
  IconRefresh,
  IconPlus,
  IconUpload,
  IconDownload,
  IconEdit,
  IconDelete
} from '@arco-design/web-vue/es/icon';
import JSZip from 'jszip';
import QRCode from 'qrcode';

// 表格加载状态
const loading = ref(false);

// 表格数据
const tableData = ref<ChargingData[]>([]);

// 站点列表
const stationList = ref<{ id: number; name: string }[]>([]);

// 获取站点列表
const fetchStationList = async () => {
  try {
    const res = await getAllCarChargingGroups();
    if (res.code === 200 && res.data) {
      stationList.value = Array.isArray(res.data) ? res.data : [];
    } else {
      Message.error(res.message || '获取站点列表失败');
    }
  } catch (error) {
    console.error('获取站点列表失败:', error);
    Message.error('获取站点列表失败');
  }
};

// 搜索表单数据
const searchForm = reactive<Partial<ChargingListParams & { status?: number }>>({
  code: '',
  name: '',
  chargingGroupId: undefined,
  status: undefined,
});

// 分页配置
const pagination = reactive({
  total: 0,
  current: 1,
  pageSize: 10,
  showTotal: true,
  showJumper: true,
  showPageSize: true,
});

// 对话框相关
const dialogVisible = ref(false);
const isEdit = ref(false);
const formRef = ref<FormInstance>();

// 表单数据
const form = reactive<Partial<ChargingData>>({
  id: undefined,
  code: '',
  name: '',
  socketCount: 1,
  chargingGroupId: undefined,
  status: 1,
});

// 表单验证规则
const rules = {
  code: [{ required: true, message: '请输入设备编号' }],
  socketCount: [{ required: true, message: '请输枪数量' }],
};

// 选中的行keys
const selectedKeys = ref<string[]>([]);

// 是否有选中行
const hasSelected = computed(() => selectedKeys.value.length > 0);

// 获取表格数据
const fetchData = async () => {
  loading.value = true;
  try {
    const params: ChargingListParams & { status?: number } = {
      pageNum: pagination.current,
      pageSize: pagination.pageSize,
      ...searchForm,
    };
    const res = await getChargingList(params);
    if (res.code === 200 && res.data) {
      // 安全访问分页数据
      const pageData = res.data as any;
      tableData.value = pageData.records || [];
      pagination.total = pageData.total || 0;
    } else {
      Message.error(res.message || '获取数据失败');
    }
  } catch (error) {
    console.error('获取数据失败:', error);
    Message.error('获取数据失败');
  } finally {
    loading.value = false;
  }
};

// 搜索
const search = () => {
  pagination.current = 1;
  fetchData();
};

// 重置搜索
const reset = () => {
  searchForm.code = '';
  searchForm.name = '';
  searchForm.chargingGroupId = undefined;
  searchForm.status = undefined;
  search();
};

// 分页变化
const onPageChange = (current: number) => {
  pagination.current = current;
  fetchData();
};

// 每页条数变化
const onPageSizeChange = (pageSize: number) => {
  pagination.pageSize = pageSize;
  pagination.current = 1;
  fetchData();
};

// 打开新增对话框
const openAddDialog = () => {
  isEdit.value = false;
  form.id = undefined;
  form.code = '';
  form.name = '';
  form.socketCount = 1;
  form.chargingGroupId = undefined;
  form.status = 0;
  dialogVisible.value = true;
};

// 打开编辑对话框
const openEditDialog = (record: ChargingData) => {
  isEdit.value = true;
  form.id = record.id;
  form.code = record.code;
  form.name = record.name;
  form.socketCount = record.socketCount;
  form.status = record.status;
  form.chargingGroupId = record.chargingGroupId;

  // 检查数据完整性
  console.log('打开编辑对话框，原始记录:', record);
  console.log('设置表单数据:', form);

  dialogVisible.value = true;

  // 等待DOM更新后设置表单值
  nextTick(() => {
    if (chargingFormRef.value) {
      const formData = {
        code: record.code,
        name: record.name,
        socketCount: record.socketCount,
        chargingGroupId: record.chargingGroupId
      };
      console.log('设置子组件表单数据:', formData);
      chargingFormRef.value.setFormData(formData);
    }
  });
};

// 关闭对话框
const closeDialog = () => {
  dialogVisible.value = false;
  if (!isEdit.value) {
    chargingFormRef.value?.resetForm();
  }
};

// 表单引用
const chargingFormRef = ref();

// 计算edit-data属性
const editData = computed(() => {
  if (!isEdit.value) return undefined;
  return {
    id: form.id,
    code: form.code || '',
    name: form.name || '',
    socketCount: form.socketCount || 1,
    chargingGroupId: form.chargingGroupId
  };
});

// 提交表单
const handleSubmit = async () => {
  try {
    // 使用子组件的验证方法
    await chargingFormRef.value?.validate();

    // 获取子组件的表单数据
    const formData = chargingFormRef.value?.getFormData();
    if (!formData) return false;

    console.log('调试信息 - 表单数据:', formData);
    console.log('调试信息 - code值:', formData.code);

    if (isEdit.value && form.id) {
      // 编辑
      const res = await updateCharging({
        ...formData,
        id: form.id,
        status: form.status
      });
      if (res.code === 200) {
        Message.success('编辑成功');
        closeDialog();
        fetchData();
      } else {
        Message.error(res.message || '编辑失败');
      }
    } else {
      // 新增
      const res = await addCharging({
        ...formData,
        status: 0 // 默认离线状态
      });
      if (res.code === 200) {
        Message.success('新增成功');
        closeDialog();
        fetchData();
      } else {
        Message.error(res.message || '新增失败');
      }
    }
  } catch (error) {
    console.error('表单提交失败:', error);
    return false;
  }
};

// 删除
const handleDelete = (record: ChargingData) => {
  Modal.confirm({
    title: '确认删除',
    content: `确定要删除设备编号为 "${record.code}" 的充电桩吗？`,
    onOk: async () => {
      try {
        const res = await deleteCharging(record.id);
        if (res.code === 200) {
          Message.success('删除成功');
          fetchData();
        } else {
          Message.error(res.message || '删除失败');
        }
      } catch (error) {
        console.error('删除失败:', error);
        Message.error('删除失败');
      }
    },
  });
};

// 导入对话框状态
const importVisible = ref(false);

// 打开导入对话框
const openImportDialog = () => {
  importVisible.value = true;
};

// 处理导入成功
const handleImportSuccess = () => {
  fetchData();
};

// 生成带设备编号的二维码图片
const generateQRCodeWithLabel = async (url: string, label: string): Promise<string> => {
  // 先生成二维码图片
  const qrCodeDataURL = await QRCode.toDataURL(url, {
    errorCorrectionLevel: 'H',
    margin: 1,
    width: 300,
    color: {
      dark: '#000000',
      light: '#ffffff'
    }
  });

  // 创建一个临时canvas
  const canvas = document.createElement('canvas');
  const ctx = canvas.getContext('2d');
  if (!ctx) {
    throw new Error('无法获取canvas上下文');
  }

  // 设置canvas尺寸
  canvas.width = 300;
  canvas.height = 340; // 为标签留出空间

  // 创建图像对象
  const img = new Image();

  // 等待图像加载
  await new Promise<void>((resolve, reject) => {
    img.onload = () => resolve();
    img.onerror = reject;
    img.src = qrCodeDataURL;
  });

  // 绘制二维码图像
  ctx.fillStyle = '#FFFFFF';
  ctx.fillRect(0, 0, canvas.width, canvas.height);
  ctx.drawImage(img, 0, 0, 300, 300);

  // 绘制标签文本
  ctx.fillStyle = '#000000';
  ctx.font = 'bold 14px Arial';
  ctx.textAlign = 'center';
  ctx.fillText(label, canvas.width / 2, 320);

  // 返回结果图像的数据URL
  return canvas.toDataURL('image/png');
};

// 导出二维码
const handleExportQrCodes = async () => {
  if (selectedKeys.value.length === 0) {
    Message.warning('请选择需要导出二维码的充电桩');
    return;
  }

  console.log('选中的充电桩IDs:', selectedKeys.value);

  try {
    // 调用后端接口获取二维码
    const ids = selectedKeys.value.join(',');
    console.log('请求的IDs:', ids);
    const res = await getChargingQrCodes(ids);

    if (res.code === 200 && Array.isArray(res.data)) {
      // 创建一个临时的ZIP文件
      const zip = new JSZip();

      // 遍历每个充电桩的二维码
      for (const item of res.data) {
        // 为每个充电桩创建一个文件夹
        const folder = zip.folder(item.chargingCode);
        if (folder) {
          // 将二维码图片添加到对应的文件夹中
          for (const qrCode of item.qrCodes) {
            try {
              // 生成带设备编号的二维码图片
              const qrCodeDataURL = await generateQRCodeWithLabel(
                qrCode.qrCode,
                `设备编号: ${qrCode.chargingCode}`
              );

              // 将base64图片数据转换为二进制
              const base64Data = qrCodeDataURL.split(',')[1];
              if (!base64Data) {
                console.warn(`二维码数据格式错误: ${qrCode.chargingName}`);
                continue;
              }
              const imageData = atob(base64Data);
              const arrayBuffer = new ArrayBuffer(imageData.length);
              const uint8Array = new Uint8Array(arrayBuffer);
              for (let i = 0; i < imageData.length; i++) {
                uint8Array[i] = imageData.charCodeAt(i);
              }

              // 添加信息文本文件，显示编号和URL
              folder.file(`${qrCode.chargingName}_${qrCode.chargingCode}_info.txt`,
                `充电桩名称: ${qrCode.chargingName}\n` +
                `充电桩编号: ${qrCode.chargingCode}\n` +
                `二维码链接: ${qrCode.qrCode}`
              );

              // 添加二维码图片
              folder.file(`${qrCode.chargingCode}.png`, uint8Array);
            } catch (error) {
              console.error(`生成二维码失败: ${qrCode.chargingName}`, error);
            }
          }
        }
      }

      // 生成ZIP文件并下载
      const zipBlob = await zip.generateAsync({ type: 'blob' });
      const downloadLink = document.createElement('a');
      downloadLink.href = URL.createObjectURL(zipBlob);
      downloadLink.download = '充电桩二维码.zip';
      document.body.appendChild(downloadLink);
      downloadLink.click();
      document.body.removeChild(downloadLink);
      URL.revokeObjectURL(downloadLink.href);

      Message.success('二维码导出成功');
    } else {
      throw new Error(res.message || '获取二维码失败');
    }
  } catch (error) {
    console.error('导出二维码失败:', error);
    Message.error('导出二维码失败');
  }
};

onMounted(() => {
  fetchData();
  fetchStationList();
});
</script>

<style scoped lang="less">
.container {
  padding: 0 20px 20px 20px;
}

:deep(.arco-table-th) {
  &:last-child {
    .arco-table-th-item-title {
      margin-left: 16px;
    }
  }
}

.filter-container {
  margin-bottom: 20px;
  padding: 16px 20px;
  background: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.filter-row {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  margin: 0 -10px;
}

.filter-item {
  display: flex;
  align-items: center;
  margin: 0 10px 10px 10px;
}

.filter-label {
  font-size: 14px;
  font-weight: normal;
  color: var(--color-text-2);
  margin-right: 8px;
  white-space: nowrap;
}

.filter-input {
  width: 200px;
}

.filter-select {
  width: 200px;
}

.filter-actions {
  .reset-btn {
    margin-left: 8px;
  }

  .add-btn {
    margin-left: 8px;
  }

  .import-btn {
    margin-left: 8px;
  }

  .export-btn {
    margin-left: 8px;
  }
}

.action-btns {
  display: flex;
  justify-content: center;
}
</style>